package cn.hchaojie.camp.day13;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class ClientFx extends Application {
	private Socket socket;
	private DataOutputStream os;
	
	@Override
	public void start(Stage primaryStage) throws Exception {
		VBox box = new VBox(10);
		box.setPadding(new Insets(10));
		
		// 多行输入框
		TextArea ta = new TextArea();
		VBox.setVgrow(ta, Priority.ALWAYS);
		
		// 单行输入
		TextField tf = new TextField();
		box.getChildren().addAll(ta, tf);

		// 监听回车事件
//		tf.setOnKeyPressed(new EventHandler<KeyEvent>() {
//			@Override
//			public void handle(KeyEvent event) {
//				
//			}
//		});
		tf.setOnKeyPressed((event) -> {
			KeyCode code = event.getCode();
			if (code == KeyCode.ENTER) {
				String message = tf.getText();
				if ("".equals(message)) {
					return;
				}
				
				ta.appendText(message + "\n");
				tf.setText("");
				
				if ("88".equals(message)) {
					// 客户端结束的逻辑处理
					Utils.closeQuietly(os);
					Utils.closeQuietly(socket);
					System.exit(0);
				}
				
				try {
					os.writeUTF(message);
					os.flush();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
		
		Scene scene = new Scene(box, 500, 300);
		primaryStage.setScene(scene);
		primaryStage.show();
		
		openSocket();
	}
	
	private void openSocket() {
		// host:主机 port：端口
		try {
			socket = new Socket("127.0.0.1", 6666);
			os = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
			System.out.println("和服务器已经连上了。。。");
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void stop() throws Exception {
		super.stop();
		
		// 关闭资源
		Utils.closeQuietly(os);
		Utils.closeQuietly(socket);
	}

	public static void main(String[] args) {
		launch(args);
	}
}
